package com.dhcc.DRGsHosp.web.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.security.shiro.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.dhcc.DRGsHosp.facade.BenchmarkFileUploadFacade;
import com.dhcc.DRGsHosp.facade.DepGroupFacade;
import com.dhcc.DRGsHosp.facade.DepartmentFacade;
import com.dhcc.DRGsHosp.facade.FileUploadFacade;
import com.dhcc.DRGsHosp.facade.GroupFuncFacade;
import com.dhcc.DRGsHosp.facade.ICDFacade;
import com.dhcc.DRGsHosp.facade.MiMonthProPortionFacade;
import com.dhcc.DRGsHosp.facade.UserInfoFileUploadFacade;
import com.dhcc.DRGsHosp.facade.dto.ManageSummaryDTO;
import com.dhcc.DRGsHosp.facade.dto.MiMonthProPortionDTO;
import com.dhcc.DRGsHosp.infra.util.GlobalData;

/**
 * @title :FileUploadController.java
 * @description :
 * @author :liqingyang
 * @date :2015年5月12日
 * @version :1.0
 * @copyright :DHCC 2013-2014
 */
@Controller("drgsHospWebController18")
@RequestMapping("/fileUpload")
public class FileUploadController {
	
	@Autowired
	private FileUploadFacade fileUploadFacade;
	
	@Autowired
	private UserInfoFileUploadFacade userInfoFileUploadFacade;
	
	@Autowired
	private MiMonthProPortionFacade miMonthProPortionFacade;
	
	@Autowired
	private GroupFuncFacade groupFuncFacade;
	
	@Autowired
	private DepartmentFacade departmentFacade;
	
	@Autowired
	private DepGroupFacade depGroupFacade;
	
	@Autowired
	private ICDFacade icdFacade;
	
	@Autowired
	private BenchmarkFileUploadFacade benchmarkFileUploadFacade;
	
	private Map<String, Object> groupResult = new HashMap<String, Object>();
	
	private boolean flag = true;
	
	List<String> filesPath = new ArrayList<String>();// 上传成功的文件路径


	/**
	 * 
	 * @methodname    :filesUpload
	 * @description   :多个文件上传
	 * @param         :
	 * @author        :liqingyang
	 * @return        :
	 * @date          :2015年5月13日
	 */
	@ResponseBody
	@RequestMapping("/filesUpload")  
    public InvokeResult filesUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {  
		 filesPath = new ArrayList<String>();//每次调用清空文件路径
		String fileCat = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//定义一个随时间变化的变量，加在filename前，使上传的文件不重复
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
                //记录上传过程起始时的时间，用来计算上传时间  
                int pre = (int) System.currentTimeMillis();  
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){

                        System.out.println(myFileName);  
                        //重命名上传后的文件名  
                        String fileName = fileCat+"_"+ file.getOriginalFilename();  
                        //定义上传路径  
                        String path = request.getSession().getServletContext().getRealPath("/")+"upload";
                        File localFile = new File(path);
                        if (!localFile.exists()) {
							localFile.mkdirs();
						}
                        localFile = new File(path + File.separatorChar + fileName);
                        try {
							file.transferTo(localFile);
							filesPath.add(path + File.separatorChar + fileName);
						} catch (Exception e) {
							e.printStackTrace();
						}//文件上传至服务器  
                    }  
                }  
                //记录上传该文件后的时间  
                int finaltime = (int) System.currentTimeMillis();  
                System.out.println("本文件上传时间："+(finaltime - pre)+"ms");  
            }  
              
        }  
        return InvokeResult.success();
    }  
	
	/**
	 * 
	 * @methodname    :importMedicalRecord
	 * @description   :导入首页基础数据
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月25日
	 */
	@ResponseBody
	@RequestMapping("/importMedicalRecord"  )  
    public InvokeResult importMedicalRecord(HttpServletRequest request,HttpServletResponse response){ 
        InvokeResult iResult = InvokeResult.success();
        int cur = 1;
        int all = filesPath.size();
        for (String filePath : filesPath) {
        	iResult = fileUploadFacade.importMedicalRecord(filePath, request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/",cur,all);
        	cur++;
		}
        filesPath.clear();
        return iResult;
    }
	
	/**
	 * 
	 * @methodname    :importDRGs
	 * @description   :导入DRGs基础数据
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月26日
	 */
	@ResponseBody
	@RequestMapping("/importDRGs"  )  
    public InvokeResult importDRGs(HttpServletRequest request,HttpServletResponse response){  
		InvokeResult iResult = InvokeResult.success();
        for (String filePath : filesPath) {
        	iResult = fileUploadFacade.importDRGs(filePath);
		}
        filesPath.clear();
        return iResult;
    }
	
	/**
	 * 
	 * @methodname    :importHCData
	 * @description   :导入医保数据
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月26日
	 */
	@ResponseBody
	@RequestMapping("/importHCData")  
    public InvokeResult importHCData(HttpServletRequest request,HttpServletResponse response, String user_guid){  
        InvokeResult iResult = InvokeResult.success();
        int cur = 1;
        int all = filesPath.size();
        for (String filePath : filesPath) {
			iResult = fileUploadFacade.importHCData(filePath,cur,all, user_guid);
			cur++;
		}
        filesPath.clear();
        return iResult;
    }
	
	
	/**
	 * 
	 * @methodname    :addMonthProportion
	 * @description   :保存医保总额每月分配比例
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月22日
	 */
	@ResponseBody
	@RequestMapping("/addHCTotalFund"  )  
    public InvokeResult addHCTotalFund(@RequestParam String HCTotalFundYear,@RequestParam String HCTotalFund){
		miMonthProPortionFacade.addHCTotalFund(HCTotalFundYear,HCTotalFund);
		return InvokeResult.success();
	}
	
	/**
	 * 
	 * @methodname    :addMonthProportion
	 * @description   :保存医保总额每月分配比例
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月22日
	 */
	@ResponseBody
	@RequestMapping("/addMonthProportion"  )  
    public InvokeResult addMonthProportion(@RequestParam String jsonStr){
		ObjectMapper objectMapper=new ObjectMapper();
		MiMonthProPortionDTO miMonthproportion = new MiMonthProPortionDTO();
		
		Map<String, Object> reusltMap = new HashMap<String, Object>();
		try {
			//把字符串转成map	
			reusltMap = objectMapper.readValue(jsonStr, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		for (Map.Entry<String, Object> entry : reusltMap.entrySet()) {
			String month=entry.getKey();
			double value=(Double) entry.getValue();
			miMonthproportion.setMimpMonth(month);
			miMonthproportion.setMimpValue(value);
			miMonthProPortionFacade.creatMiMonthProPortion(miMonthproportion);
		}
		
		return InvokeResult.success();
	}
	

	
	/**
	 * 
	 * @methodname    :getNoDataDay
	 * @description   :查询日监测表中，没有数据的日期（当前日期起，3个月内）,并反馈给前台提示。注意，补录数据时会重新取一次日期。
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月27日
	 */
	@ResponseBody
	@RequestMapping("/getNoDataDay"  )  
    public InvokeResult getNoDataDay(String hospCode){  
        return fileUploadFacade.getNoDataDay(hospCode);
    }
	
	/**
	 * @methodname    :getProgress
	 * @description   :获取执行进度
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年1月27日
	 */
	@ResponseBody
	@RequestMapping("/getProgress"  ) 
	public void getProgress(HttpServletRequest request,HttpServletResponse response){
		fileUploadFacade.getProgress(response);
	}
	/**
	 * 
	 * @methodname    :requestProgress
	 * @description   :请求执行进度
	 * @param         :
	 * @author        :mazhaoyan
	 * @return        :
	 * @date          :2016年6月3日
	 */
	@ResponseBody
	@RequestMapping("/requestProgress"  ) 
	public InvokeResult requestProgress(){
		Map<String,Object> processInfo = fileUploadFacade.requestProgress();
		return InvokeResult.success(processInfo);
	}
	
	/**
	 * 
	 * @methodname    :uploadProgress 
	 * @description   :请求执行进度
	 * @param         :
	 * @author        :chenhanlin
	 * @return        :
	 * @date          :2017年6月17日
	 */
	@ResponseBody
	@RequestMapping("/uploadProgress") 
	public InvokeResult uploadProgress(){
		 return benchmarkFileUploadFacade.uploadProgress();
	}
	
	
	/**
	 * 
	 * @methodname    :drgsGroup
	 * @description   :页面级分组
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年12月18日
	 */
	@ResponseBody
	@RequestMapping("/drgsGroup"  )  
    public Map<String, Object> drgsGroup(HttpServletRequest request,HttpServletResponse response){
		flag = true;
        String groupVersion = request.getParameter("groupVersion");
        String isICDMatch = request.getParameter("isICDMatch");
        for (String filePath : filesPath) {
        	groupResult = groupFuncFacade.drgsGroupExcel(filePath, request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/",groupVersion,isICDMatch);
		}
        flag = false;
        return groupResult;
    }
	
	@ResponseBody
	@RequestMapping("/getGroupResult"  )  
    public Map<String, Object> getGroupResult(){
		while (flag) {
			try {
				Thread.sleep(400);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return groupResult;
    }

	
	@ResponseBody
	@RequestMapping("/continueUpload")
	public InvokeResult continueUpload(String user_guid, String operation){
		GlobalData.cookie.put(user_guid, "1");
		GlobalData.cookie.put(user_guid+"_operation", operation);
		return InvokeResult.success();
	}
	
	
	/**
	 * 
	 * @methodname    :judgeManage
	 * @description   : 判断是否已有标杆
	 * @param         :
	 * @author        :mazhaoyan
	 * @return        :
	 * @date          :2016年10月13日
	 */
	@ResponseBody
	@RequestMapping("/judgeManage")  
    public InvokeResult judgeManage(ManageSummaryDTO dto) throws Exception {  
		return fileUploadFacade.judgeManage(dto);
    }
	
	@ResponseBody
	@RequestMapping("/getProcess")  
    public InvokeResult getProcess() throws Exception {  
		return fileUploadFacade.getProcess();
    }
	
	/**
	 * 
	 * @methodname    : importexternalBenchmarkData
	 * @description   : 外部标杆数据导入
	 * @param         :
	 * @author        :chenhanlin
	 * @return        :
	 * @date          :2017年6月12日
	 */
	@ResponseBody
	@RequestMapping("/importExternalBenchmarkData")  
    public InvokeResult importexternalBenchmarkData(HttpServletRequest request,HttpServletResponse response,String parMscode) throws Exception {  
		InvokeResult iResult = InvokeResult.success();
        for (String filePath : filesPath) {
        	iResult = benchmarkFileUploadFacade.importExternalBenchmarkData (filePath,CurrentUser.getRoleName(),parMscode) ;
		}
        filesPath.clear();
        return iResult;
    }
	
	/**
	 * 
	 * @methodname    : importCalculateBenchmark
	 * @description   :  计算标杆数据导入
	 * @param         :
	 * @author        :chenhanlin
	 * @return        :
	 * @date          :2017年6月12日
	 */
	@ResponseBody
	@RequestMapping("/importCalculateBenchmark")  
	public InvokeResult importCalculateBenchmark(HttpServletRequest request,HttpServletResponse response,String drgVersion,String calculateType) throws Exception {  
		InvokeResult iResult = InvokeResult.success();
		System.out.println("benchmarkFileUploadFacade 对象 ：" + benchmarkFileUploadFacade.toString());
		for (String filePath : filesPath) {
			iResult = benchmarkFileUploadFacade.importCalculateBenchmark (filePath,drgVersion,calculateType) ;
		}
		filesPath.clear();
		return iResult;
	}
	
	/**
	 * 
	 * @methodname    : importPerformanceBenchmark
	 * @description   : 绩效标杆数据导入
	 * @param         :
	 * @author        :chenhanlin
	 * @return        :
	 * @date          :2017年6月12日
	 */
	@ResponseBody
	@RequestMapping("/importPerformanceBenchmark")  
	public InvokeResult importPerformanceBenchmark(HttpServletRequest request,HttpServletResponse response,String parMscode)  throws Exception {  
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = benchmarkFileUploadFacade.importPerformanceBenchmark (filePath,CurrentUser.getRoleName(),parMscode);
		}
		filesPath.clear();
		return iResult;
	}
	
	/**
	 * 
	 * @methodname    : userImport
	 * @description   : 用户数据批量导入
	 * @param         :
	 * @author        :chenhanlin
	 * @return        :
	 * @date          :2017年7月14日
	 */
	@ResponseBody
	@RequestMapping("/userImport")  
	public InvokeResult userImport(HttpServletRequest request,HttpServletResponse response)  throws Exception {  
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = userInfoFileUploadFacade.userImport(filePath,CurrentUser.getUserAccount());
		}
		filesPath.clear();
		return iResult;
	}
	
	/**
	 *  费用子项导入
	 *  costSubImport.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @return
	 *  @throws Exception 
	 *  @Date:2018年3月15日上午11:32:36
	 */
	@ResponseBody
	@RequestMapping("/costSubImport")  
	public InvokeResult costSubImport()  throws Exception {  
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = fileUploadFacade.costSubImport(filePath);
		}
		filesPath.clear();
		return iResult;
	}
	
	@ResponseBody
	@RequestMapping("/doctorInfoImport")  
	public InvokeResult doctorInfoImport()  throws Exception {  
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = fileUploadFacade.doctorInfoImport(filePath);
		}
		filesPath.clear();
		return iResult;
	}
	
	/**
	 * 
	 *  depGroupImport.  
	 *  @Description：科室组数据导入
	 *  @Author WENYI
	 *  @param request
	 *  @param response
	 *  @return 
	 *  @Date:2018年3月14日下午5:10:54
	 */
	@ResponseBody
	@RequestMapping("/depGroupImport")  
	public InvokeResult depGroupImport(HttpServletRequest request,HttpServletResponse response){
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = depGroupFacade.depGroupImport(filePath);
		}
		filesPath.clear();
		return iResult;
	}
	/**
	 * 
	 *  departmentImport.  
	 *  @Description：科室数据导入
	 *  @Author WENYI
	 *  @param request
	 *  @param response
	 *  @return 
	 *  @Date:2018年3月14日下午5:10:46
	 */
	@ResponseBody
	@RequestMapping("/departmentImport")  
	public InvokeResult departmentImport(HttpServletRequest request,HttpServletResponse response){
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = departmentFacade.departmentImport(filePath);
		}
		filesPath.clear();
		return iResult;
	}
	
	@ResponseBody
	@RequestMapping("/wardImport")  
	public InvokeResult wardImport(HttpServletRequest request,HttpServletResponse response){
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = fileUploadFacade.wardImport(filePath);
		}
		filesPath.clear();
		return iResult;
	}
	/**
	 * 
	 *  ICDMatchBigData.  
	 *  @Description：调用大数据接口，ICD对照
	 *  @Author WENYI
	 *  @param contrastType
	 *  @param contrastVersion
	 *  @param contrastResultCnt
	 *  @return 
	 *  @Date:2018年3月30日下午2:26:31
	 */
	@ResponseBody
	@RequestMapping("/ICDMatchBigData")  
	public InvokeResult ICDMatchBigData(String contrastType,String contrastVersion,String contrastResultCnt){
		InvokeResult iResult = InvokeResult.success();
		for (String filePath : filesPath) {
			iResult = icdFacade.ICDMatchBigData(filePath,contrastType,contrastVersion,contrastResultCnt);
		}
		filesPath.clear();
		return iResult;
	}
	/**
	 * 
	 * @Title: getAbnomalGroupCase  
	 * @Description:分组异常数据系统导出
	 * @param @param contrastType
	 * @param @return   
	 * @return InvokeResult  
	 * @author shaozhiyuan
	 * @date 2018年5月16日  
	 * @version V3.1.0 
	 * @throws
	 */
	@ResponseBody
	@RequestMapping("/getAbnomalGroupCase")  
	public InvokeResult getAbnomalGroupCase(String medicalRecordNumber){
		String mrNumber=medicalRecordNumber==null?"":medicalRecordNumber.toString().trim();
		return InvokeResult.success(fileUploadFacade.getAbnomalGroupCase(mrNumber));
	}
	
	/**
	 * 
	 *  @Description：更新ipinfo表的标识位(长庚个性化需求）
	 *  @Author fulianxia
	 *  @param datefrom
	 *  @param dateto
	 *  @return
	 *  @Date:2018年3月23日
	 */
	@ResponseBody
	@RequestMapping("/saveConfirmFlag")  
	public InvokeResult saveConfirmFlag(String datefrom,String dateto){  
		return fileUploadFacade.saveConfirmFlag(datefrom, dateto);
	}
	
	/**
	 * 
	 *  @Description：查询license中的医院名称(长庚个性化需求）
	 *  @Author fulianxia
	 *  @return
	 *  @Date:2018年12月26日
	 */
	@ResponseBody
	@RequestMapping("/getLicenseHospName")  
	public InvokeResult getLicenseHospName(){  
		return InvokeResult.success(GlobalData.hospName);
	}
	
	
}
